<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;padding: 15px 20px;background-color: #f8f9fa;border-radius: 6px;">
        <el-form :inline="true" class="search-form">
          <el-form-item label="关键词">
            <el-input
              v-model="keyword"
              placeholder="订单编号/订单名称/供应商名称/备注/进展"
              style="width: 250px;"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="status_filter" placeholder="请选择状态" style="width: 120px;" clearable>
              <el-option label="全部" value="" />
              <el-option label="开启" value="open" />
              <el-option label="等待" value="pending" />
              <el-option label="完成" value="completed" />
              <el-option label="取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
            <el-button type="success" icon="el-icon-plus" :disabled="listLoading" @click="handleAction('create', '添加')">添加采购信息</el-button>
            <el-button type="info" icon="el-icon-data-line" :disabled="listLoading" @click="showStatistics">统计信息</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <!-- 统计信息 -->
        <div v-if="statistics" class="statistics-bar">
          <div class="stat-item">
            <span class="stat-label">总数</span>
            <span class="stat-value">{{ statistics.total }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">开启中</span>
            <span class="stat-value stat-open">{{ statistics.open }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">等待中</span>
            <span class="stat-value stat-pending">{{ statistics.pending }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已完成</span>
            <span class="stat-value stat-completed">{{ statistics.completed }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已取消</span>
            <span class="stat-value stat-cancelled">{{ statistics.cancelled }}</span>
          </div>
        </div>

        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <!-- 订单信息（单号[名称]-状态） -->
          <el-table-column label="订单信息" min-width="300">
            <template slot-scope="scope">
              <div class="order-info-cell">
                <div class="order-info-line">
                  <el-button
                    type="text"
                    style="color: #409EFF; font-weight: bold; padding: 0;"
                    @click="showOrderDetail(scope.row.crmorder_data)"
                  >
                    {{ scope.row.crmorder_data.order_no }}
                  </el-button>
                  <span class="order-name-bracket">[{{ scope.row.crmorder_data.name }}]</span>
                  <span class="order-state-name" :style="{ color: scope.row.crmorder_data.crmorderstate_color }">-{{ scope.row.crmorder_data.crmorderstate_name }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 供应商 -->
          <el-table-column prop="crmsupplier_data.name" label="供应商" width="180">
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  style="color: #E6A23C; font-weight: bold;"
                  @click="showSupplierDetail(scope.row.crmsupplier_data)"
                >
                  {{ scope.row.crmsupplier_data && scope.row.crmsupplier_data.name || '无供应商信息' }}
                </el-button>
                <div v-if="scope.row.crmsupplier_data.wechatgroup" class="supplier-wechatgroup">
                  <i class="el-icon-chat-dot-round" style="color: #67C23A;" />
                  {{ scope.row.crmsupplier_data.wechatgroup }}
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 进展 -->
          <el-table-column prop="progress" label="进展" min-width="220">
            <template slot-scope="scope">
              <!-- 编辑状态 -->
              <div v-if="scope.row.editingProgress" class="edit-progress-container">
                <el-input
                  v-model="scope.row.tempProgress"
                  type="textarea"
                  :rows="2"
                  size="mini"
                  placeholder="请输入进展内容（可多行）"
                  style="flex: 1;"
                  @keyup.ctrl.enter.native="saveQuickProgress(scope.row)"
                  @blur="handleProgressBlur(scope.row, $event)"
                />
                <div class="edit-buttons">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-check"
                    @click="saveQuickProgress(scope.row)"
                  />
                  <el-button
                    size="mini"
                    type="info"
                    icon="el-icon-close"
                    @click="cancelEditProgress(scope.row)"
                  />
                </div>
              </div>
              <!-- 显示状态 -->
              <div v-else class="show-progress-container">
                <div
                  class="progress-content"
                  :title="scope.row.progress || '点击编辑进展'"
                  @click="editProgress(scope.row)"
                >
                  <div class="progress-text">
                    <span v-if="scope.row.progress">{{ scope.row.progress }}</span>
                    <span v-else class="progress-placeholder">暂无进展，点击编辑</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 备注 -->
          <el-table-column prop="current_remark" label="备注" min-width="220">
            <template slot-scope="scope">
              <div class="remark-cell">
                <!-- 编辑状态 -->
                <div v-if="scope.row.editingRemark" class="edit-remark-container">
                  <el-input
                    v-model="scope.row.tempRemark"
                    type="textarea"
                    :rows="2"
                    size="mini"
                    placeholder="请输入备注内容（可多行）"
                    style="flex: 1;"
                    @keyup.ctrl.enter.native="saveQuickRemark(scope.row)"
                    @blur="handleRemarkBlur(scope.row, $event)"
                  />
                  <div class="edit-buttons">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-check"
                      @click="saveQuickRemark(scope.row)"
                    />
                    <el-button
                      size="mini"
                      type="info"
                      icon="el-icon-close"
                      @click="cancelEditRemark(scope.row)"
                    />
                  </div>
                </div>
                <!-- 显示状态 -->
                <div v-else class="show-remark-container">
                  <div
                    class="remark-content"
                    :title="scope.row.current_remark || '点击编辑备注'"
                    @click="editRemark(scope.row)"
                  >
                    <div class="remark-text">
                      <span v-if="scope.row.current_remark">{{ scope.row.current_remark }}</span>
                      <span v-else class="remark-placeholder">暂无备注，点击编辑</span>
                    </div>
                  </div>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-chat-line-square"
                    title="查看备注历史"
                    @click="showRemarksHistory(scope.row)"
                  >
                    ({{ scope.row.remarks_count }})
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 最后跟进 -->
          <el-table-column prop="last_follow_time_short" label="最后跟进" width="120" />
          <!-- 跟进人 -->
          <el-table-column prop="creator_name" label="跟进人" width="100" />
          <!-- 协作者 -->
          <el-table-column label="协作者" width="150">
            <template slot-scope="scope">
              <div class="collaborators-cell">
                <div v-if="scope.row.collaborators && scope.row.collaborators.length > 0" class="collaborators-list">
                  <el-tag
                    v-for="(collaborator, index) in scope.row.collaborators.slice(0, 2)"
                    :key="collaborator.id"
                    size="mini"
                    type="info"
                    style="margin: 1px 2px;"
                  >
                    {{ collaborator.full_name }}
                  </el-tag>
                  <span v-if="scope.row.collaborators.length > 2" class="more-collaborators">
                    +{{ scope.row.collaborators.length - 2 }}
                  </span>
                </div>
                <span v-else class="no-collaborators">无协作者</span>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  title="管理协作者"
                  @click="manageCollaborators(scope.row)"
                >
                  管理
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="320">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-money"
                style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                @click="handleAddPayment(scope.row)"
              >
                新增付款
              </el-button>
              <el-button size="mini" type="primary" @click="handleAction('edit', scope.row)">编辑</el-button>
              <el-button size="mini" type="warning" @click="addRemark(scope.row)">备注</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="form_dialog_title"
      :visible.sync="form_dialog_visible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="选择订单" prop="crmorder_id">
          <el-select
            v-model="form.crmorder_id"
            placeholder="请输入关键词搜索订单"
            style="width: 100%;"
            filterable
            remote
            reserve-keyword
            :remote-method="searchOrders"
            :loading="orderSearchLoading"
          >
            <el-option
              v-for="order in orderOptions"
              :key="order.id"
              :label="`${order.order_no} - ${order.name}`"
              :value="order.id"
            >
              <span style="float: left">{{ order.order_no }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ order.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择供应商" prop="crmsupplier_id">
          <el-select
            v-model="form.crmsupplier_id"
            placeholder="请输入关键词搜索供应商"
            style="width: 100%;"
            filterable
            remote
            reserve-keyword
            :remote-method="searchSuppliers"
            :loading="supplierSearchLoading"
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            >
              <span style="float: left">{{ supplier.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ supplier.contact_name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="开启" value="open" />
            <el-option label="等待" value="pending" />
            <el-option label="完成" value="completed" />
            <el-option label="取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="进展" prop="progress">
          <el-input
            v-model="form.progress"
            type="textarea"
            :rows="3"
            placeholder="请输入采购进展情况"
          />
        </el-form-item>
        <el-form-item label="初始备注" prop="initial_remark">
          <el-input
            v-model="form.initial_remark"
            type="textarea"
            :rows="3"
            placeholder="请输入初始备注（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="form_dialog_visible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加备注对话框 -->
    <el-dialog
      title="添加备注"
      :visible.sync="remark_dialog_visible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="remarkForm" :model="remarkForm" :rules="remarkRules" label-width="80px">
        <el-form-item label="备注内容" prop="content">
          <el-input
            v-model="remarkForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remark_dialog_visible = false">取 消</el-button>
        <el-button type="primary" :loading="remarkSubmitLoading" @click="submitRemark">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 备注历史对话框 -->
    <el-dialog
      title="备注历史"
      :visible.sync="remarks_dialog_visible"
      width="800px"
      @close="handleRemarksDialogClose"
    >
      <div
        v-loading="remarksLoading"
        element-loading-text="正在加载备注历史..."
        element-loading-spinner="el-icon-loading"
        style="max-height: 400px; min-height: 200px; overflow-y: auto;"
      >
        <div v-if="!remarksLoading && remarks.length === 0" style="text-align: center; padding: 40px; color: #909399;">
          <i class="el-icon-chat-line-square" style="font-size: 48px; margin-bottom: 16px;" />
          <p>暂无备注历史</p>
        </div>
        <el-timeline v-else-if="!remarksLoading">
          <el-timeline-item
            v-for="remark in remarks"
            :key="remark.id"
            :timestamp="`${remark.create_at_short || '时间未知'} - ${remark.creator_name || '未知用户'}`"
            placement="top"
            color="#409EFF"
          >
            <el-card shadow="hover">
              <div style="line-height: 1.6; word-wrap: break-word;">
                {{ remark.content }}
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 供应商详情对话框 -->
    <el-dialog
      title="供应商详情"
      :visible.sync="supplier_detail_visible"
      width="700px"
    >
      <div v-if="selectedSupplier">
        <el-descriptions title="供应商信息" :column="2" border>
          <el-descriptions-item label="供应商名称">
            <span style="font-weight: bold; color: #E6A23C;">{{ selectedSupplier.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ selectedSupplier.contact_name || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <span v-if="selectedSupplier.contact_phone">
              <i class="el-icon-phone" style="color: #67C23A; margin-right: 4px;" />
              {{ selectedSupplier.contact_phone }}
            </span>
            <span v-else style="color: #C0C4CC;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            <span v-if="selectedSupplier.email">
              <i class="el-icon-message" style="color: #409EFF; margin-right: 4px;" />
              {{ selectedSupplier.email }}
            </span>
            <span v-else style="color: #C0C4CC;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedSupplier.wechatgroup" label="微信群名" :span="2">
            <el-tag type="success" size="small">
              <i class="el-icon-chat-dot-round" style="margin-right: 4px;" />
              {{ selectedSupplier.wechatgroup }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 协作者管理对话框 -->
    <el-dialog
      title="管理协作者"
      :visible.sync="collaborators_dialog_visible"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-loading="collaboratorsLoading" element-loading-text="正在加载协作者信息...">
        <!-- 当前协作者列表 -->
        <div v-if="currentPurchaseCollaborators">
          <el-divider content-position="left">
            <strong>创建人</strong>
          </el-divider>
          <div class="creator-info">
            <el-tag v-if="currentPurchaseCollaborators.creator" type="success" size="medium">
              <i class="el-icon-star-on" style="margin-right: 4px;" />
              {{ currentPurchaseCollaborators.creator.full_name }}
            </el-tag>
            <span v-else class="no-creator">无创建人</span>
          </div>

          <el-divider content-position="left">
            <strong>协作者列表 ({{ (currentPurchaseCollaborators.collaborators || []).length }})</strong>
          </el-divider>

          <div class="collaborators-section">
            <div v-if="currentPurchaseCollaborators.collaborators && currentPurchaseCollaborators.collaborators.length > 0" class="current-collaborators">
              <el-tag
                v-for="collaborator in currentPurchaseCollaborators.collaborators"
                :key="collaborator.id"
                :closable="canManageCollaborators"
                type="info"
                size="medium"
                style="margin: 4px 8px 4px 0;"
                @close="removeCollaborator(collaborator.id)"
              >
                <i class="el-icon-user" style="margin-right: 4px;" />
                {{ collaborator.full_name }}
              </el-tag>
            </div>
            <div v-else class="empty-collaborators">
              <i class="el-icon-user" style="font-size: 32px; color: #C0C4CC; margin-bottom: 8px;" />
              <p style="color: #909399;">暂无协作者</p>
            </div>
          </div>

          <!-- 添加协作者 -->
          <div v-if="canManageCollaborators" class="add-collaborators-section">
            <el-divider content-position="left">
              <strong>添加协作者</strong>
            </el-divider>
            <div class="add-collaborators-form">
              <el-select
                v-model="selectedNewCollaborators"
                placeholder="搜索并选择要添加的协作者"
                multiple
                filterable
                remote
                reserve-keyword
                :remote-method="searchProjectUsers"
                :loading="userSearchLoading"
                style="width: 100%; margin-bottom: 15px;"
                @change="handleCollaboratorSelection"
              >
                <el-option
                  v-for="user in availableUsers"
                  :key="user.id"
                  :label="user.full_name"
                  :value="user.id"
                  :disabled="isUserAlreadyCollaborator(user.id)"
                >
                  <span style="float: left">{{ user.full_name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ user.username }}
                    <el-tag v-if="user.is_manager" size="mini" type="warning">管理员</el-tag>
                  </span>
                </el-option>
              </el-select>
              <div class="add-buttons">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  :disabled="!selectedNewCollaborators || selectedNewCollaborators.length === 0"
                  :loading="addCollaboratorsLoading"
                  @click="addCollaborators"
                >
                  添加选中协作者 ({{ selectedNewCollaborators ? selectedNewCollaborators.length : 0 }})
                </el-button>
              </div>
            </div>
          </div>

          <div v-else class="no-permission-tip">
            <el-alert
              title="仅创建者和管理员可以管理协作者"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="collaborators_dialog_visible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情抽屉 -->
    <crm-order-detail
      :order_data="currentOrder"
      :order-states="orderStates"
      :show-able="orderDetailVisible"
      @close="orderDetailVisible=false"
    />

    <!-- AI智能付款抽屉 -->
    <el-drawer
      title="AI智能创建应付账单"
      :visible.sync="aiPaymentDialogVisible"
      size="80%"
      :close-on-click-modal="false"
      :wrapper-closable="false"
      @close="handleAIDialogClose"
    >
      <div class="payment-drawer-content-split">
        <!-- 左侧：付款表单 (60%) -->
        <div class="left-panel-form">
          <!-- 采购单信息 -->
          <el-card v-if="selectedPurchaseForPayment" shadow="never" style="margin-bottom: 20px;">
            <div slot="header">
              <i class="el-icon-document" />
              <span>关联采购单信息</span>
            </div>
            <div class="purchase-info-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">订单号：</span>
                    <span class="info-value">{{ selectedPurchaseForPayment.crmorder_data ? selectedPurchaseForPayment.crmorder_data.order_no : '-' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">订单名称：</span>
                    <span class="info-value">{{ selectedPurchaseForPayment.crmorder_data ? selectedPurchaseForPayment.crmorder_data.name : '-' }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-top: 10px;">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">供应商：</span>
                    <span class="info-value">{{ selectedPurchaseForPayment.crmsupplier_data ? selectedPurchaseForPayment.crmsupplier_data.name : '-' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">币种：</span>
                    <span class="info-value">{{ selectedPurchaseForPayment.crmorder_data ? selectedPurchaseForPayment.crmorder_data.currency : '-' }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>

          <!-- 付款表单 -->
          <el-form ref="aiPaymentForm" :model="aiPaymentForm" :rules="aiPaymentRules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="应付金额" prop="payable_amount">
                  <el-input v-model="aiPaymentForm.payable_amount" type="number" placeholder="应付金额">
                    <template slot="append">{{ aiPaymentForm.currency }}</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="币种" prop="currency">
                  <el-select v-model="aiPaymentForm.currency" style="width: 100%;">
                    <el-option label="CNY" value="CNY" />
                    <el-option label="USD" value="USD" />
                    <el-option label="EUR" value="EUR" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="付款日期">
                  <el-date-picker
                    v-model="aiPaymentForm.payment_date"
                    type="date"
                    placeholder="选择日期（可选）"
                    style="width: 100%;"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付方式">
                  <el-select v-model="aiPaymentForm.payment_method" placeholder="请选择" style="width: 100%;">
                    <el-option label="银行转账" value="bank_transfer" />
                    <el-option label="信用证" value="letter_of_credit" />
                    <el-option label="PayPal" value="paypal" />
                    <el-option label="西联汇款" value="western_union" />
                    <el-option label="支付宝" value="alipay" />
                    <el-option label="微信支付" value="wechat" />
                    <el-option label="1688" value="1688" />
                    <el-option label="淘宝" value="taobao" />
                    <el-option label="现金" value="cash" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="交易流水号">
              <el-input v-model="aiPaymentForm.transaction_no" placeholder="银行流水号或第三方交易号" />
            </el-form-item>

            <el-form-item label="收款账号" prop="payee_account">
              <el-input v-model="aiPaymentForm.payee_account" placeholder="供应商收款账号" />
            </el-form-item>

            <el-form-item label="开户银行">
              <el-input v-model="aiPaymentForm.payee_bank" placeholder="供应商开户银行" />
            </el-form-item>

            <el-form-item label="付款项目名称" prop="notes">
              <el-input v-model="aiPaymentForm.notes" type="textarea" :rows="2" placeholder="例如：采购货款尾款、定金等" />
            </el-form-item>

            <!-- 收款账号选择 -->
            <el-form-item label="收款账号">
              <el-select
                v-model="aiPaymentForm.supplier_bank_account_id"
                placeholder="选择供应商收款账号"
                filterable
                clearable
                style="width: 100%;"
                @change="handleBankAccountChange"
              >
                <el-option
                  v-for="account in supplierBankAccounts"
                  :key="account.id"
                  :label="`${account.bank_name} - ${account.account_number.substr(-4)}`"
                  :value="account.id"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ account.bank_name }} - {{ account.account_number.substr(-4) }}</span>
                    <el-tag v-if="account.is_default" size="mini" type="success">默认</el-tag>
                  </div>
                </el-option>
              </el-select>
              <div style="margin-top: 8px;">
                <el-button type="text" size="small" @click="showAddBankAccountDialog">
                  <i class="el-icon-plus" /> 添加新收款账号
                </el-button>
              </div>
            </el-form-item>

            <!-- 底部操作按钮 -->
            <div class="form-footer">
              <el-button @click="handleAIDialogClose">取消</el-button>
              <el-button
                type="primary"
                :loading="aiCreating"
                @click="confirmCreatePayable"
              >
                确认创建应付账单
              </el-button>
            </div>
          </el-form>
        </div>

        <!-- 右侧：AI 助手 (40%) -->
        <div class="right-panel-ai">
          <div class="ai-panel-header">
            <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
            <span style="margin-left: 8px; font-weight: 600; font-size: 16px;">AI 付款助手</span>
          </div>

          <AIInnerChat
            ref="aiInnerChat"
            api-url="/crm/api/payables/ai-extract/"
            handler-name="payment_extractor"
            :context-data="paymentAIContext"
            :suggested-questions="paymentQuickActions"
            :auto-parse-json="true"
            :show-fill-button="true"
            placeholder="例如：今天付了5000美元定金给XX供应商，支付宝转账，流水号123456..."
            @fill-form="handleAIFillForm"
            @json-parsed="handleAIJsonParsed"
          />
        </div>
      </div>
    </el-drawer>

    <!-- 添加供应商收款账号对话框 -->
    <el-dialog
      title="添加供应商收款账号"
      :visible.sync="bankAccountDialogVisible"
      width="600px"
      @close="handleBankAccountDialogClose"
    >
      <el-form ref="bankAccountForm" :model="bankAccountForm" :rules="bankAccountRules" label-width="120px">
        <el-form-item label="账户名称" prop="account_name">
          <el-input v-model="bankAccountForm.account_name" placeholder="银行账户持有人名称" />
        </el-form-item>

        <el-form-item label="收款账号" prop="account_number">
          <el-input v-model="bankAccountForm.account_number" placeholder="银行账号或支付宝账号" />
        </el-form-item>

        <el-form-item label="开户银行" prop="bank_name">
          <el-input v-model="bankAccountForm.bank_name" placeholder="例如：中国工商银行、支付宝、微信支付" />
        </el-form-item>

        <el-form-item label="开户支行">
          <el-input v-model="bankAccountForm.bank_branch" placeholder="具体支行名称（选填）" />
        </el-form-item>

        <el-form-item label="账户类型" prop="account_type">
          <el-select v-model="bankAccountForm.account_type" style="width: 100%;">
            <el-option label="对公账户" value="corporate" />
            <el-option label="个人账户" value="personal" />
          </el-select>
        </el-form-item>

        <el-form-item label="币种">
          <el-select v-model="bankAccountForm.currency" style="width: 100%;">
            <el-option label="人民币 (CNY)" value="CNY" />
            <el-option label="美元 (USD)" value="USD" />
            <el-option label="欧元 (EUR)" value="EUR" />
            <el-option label="英镑 (GBP)" value="GBP" />
          </el-select>
        </el-form-item>

        <el-form-item label="收款二维码">
          <el-upload
            ref="bankAccountQrcodeUpload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="bankAccountQrcodeUploadData"
            list-type="picture-card"
            :file-list="bankAccountQrcodeList"
            :on-success="handleBankAccountQrcodeSuccess"
            :on-remove="handleBankAccountQrcodeRemove"
            :before-upload="beforeBankAccountQrcodeUpload"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div style="color: #909399; font-size: 12px;">
            上传收款二维码（支持微信、支付宝、1688等）
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="bankAccountForm.notes" type="textarea" :rows="2" placeholder="其他说明信息（选填）" />
        </el-form-item>

        <el-form-item label="设为默认">
          <el-switch v-model="bankAccountForm.is_default" />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="bankAccountDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="bankAccountCreating" @click="confirmCreateBankAccount">
          确认添加
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as crmorderpurchase from '@/api/crm/crmorderpurchase'
import { Get as GetOrderStates } from '@/api/crm/crmorderstate'
import { Get as GetCrmOrder } from '@/api/crm/crmorder'
import CrmOrderDetail from '@/views/crm/elements/crmorderdetail'
import AIInnerChat from '@/components/AIInnerChat'
import { createPayable } from '@/api/crm/payable'
import { getSupplierBankAccounts, createSupplierBankAccount } from '@/api/crm/supplierBankAccount'
import { getToken } from '@/utils/auth'
import qs from 'qs'

/**
 * 订单采购信息管理组件
 *
 * ⚠️⚠️⚠️ 重要开发提醒 ⚠️⚠️⚠️
 *
 * 📖 在前端解析数据时，请务必先查看后端对应的返回数据结构！
 *
 * 🔗 相关文件位置：
 * - 后端模型定义：kikimami_server/crm/models.py (CRMOrderPurchase, CRMOrderPurchaseRemark)
 * - API接口实现：kikimami_server/crm/api/CRMOrderPurchase_index.py
 * - 前端API调用：front_kikimami/src/api/crm/crmorderpurchase.js
 *
 * 📋 主要功能模块：
 * 1. 列表展示与搜索 - 支持关键词、状态筛选，分页显示
 * 2. 远程搜索选择 - 订单和供应商的实时搜索选择
 * 3. 快速编辑功能 - 点击内容直接编辑，支持多行输入（✨ 优化）
 *    - 点击备注/进展内容进入编辑模式
 *    - 支持多行文本输入
 *    - Ctrl+Enter 快速保存，失焦自动取消
 * 4. 订单详情查看 - 点击订单信息使用CrmOrderDetail组件展示完整详情（✨ 修正）
 * 5. 备注管理 - 查看备注历史，添加新备注
 * 6. 统计信息 - 各状态的数量统计
 *
 * 📊 表格列布局（优化后）：
 * 订单信息（单号[名称]-状态） → 供应商 → 进展 → 备注 → 最后跟进 → 跟进人 → 操作
 *
 * 📋 主要数据结构总览：
 * 1. 采购信息列表数据 - getList() ：嵌套结构 { success, data: { data: [...], total, page, pageSize } }
 *    - crmorder_data: { id, order_no, name, order_amount, currency, crmorderstate_name, crmorderstate_color }
 *    - crmsupplier_data: { id, name, contact_name, contact_phone, email, wechatgroup }
 * 2. 订单搜索结果 - searchOrders() ：直接数组 { success, data: [...] }
 * 3. 供应商搜索结果 - searchSuppliers() ：直接数组 { success, data: [...] }
 * 4. 统计数据 - getStatistics() ：扁平结构 { success, data: { total, open, completed, cancelled } }
 * 5. 备注历史数据 - showRemarksHistory() ：嵌套结构 { success, data: { data: [...] } }
 *
 * 💡 开发建议：
 * - 新增字段时，请同步更新后端模型、API接口和前端解析逻辑
 * - 修改数据结构时，请更新相关注释文档
 * - 测试时请验证所有数据字段的正确性
 */

export default {
  name: 'CRMOrderPurchase',
  components: {
    CrmOrderDetail,
    AIInnerChat
  },
  data() {
    return {
      // 列表数据
      data: [],
      total: 0,
      page: 1,
      pagesize: 20,
      listLoading: false,

      // 搜索条件
      keyword: '',
      status_filter: '',

      // 统计数据
      statistics: null,

      // 表单相关
      form_dialog_visible: false,
      form_dialog_title: '',
      form: {
        crmorder_id: '',
        crmsupplier_id: '',
        status: 'open',
        progress: '',
        initial_remark: ''
      },
      /**
       * 表单验证规则
       *
       * ⚠️ 重要提醒：在前端解析数据时，请务必先查看后端对应的返回数据结构！
       *
       * 后端API返回的数据结构参考：
       * - 订单数据：crmorder_data: { id, order_no, name, order_amount, currency }
       * - 供应商数据：crmsupplier_data: { id, name, contact_name, contact_phone, email }
       * - 状态选项：['open', 'completed', 'cancelled']
       * - 完整数据结构请参考：kikimami_server/crm/models.py CRMOrderPurchase.to_dict()
       *
       * API接口文档位置：kikimami_server/crm/api/CRMOrderPurchase_index.py
       */
      rules: {
        // 订单ID验证 - 对应后端crmorder_id字段
        crmorder_id: [
          { required: true, message: '请选择订单', trigger: 'change' }
        ],
        // 供应商ID验证 - 对应后端crmsupplier_id字段
        crmsupplier_id: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        // 状态验证 - 对应后端status字段，可选值：open/completed/cancelled
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
        // progress字段为可选，无需验证
        // initial_remark字段为可选，无需验证
      },
      submitLoading: false,

      // 选项数据
      orderOptions: [],
      supplierOptions: [],
      initialOrderOptions: [],
      initialSupplierOptions: [],

      // 搜索状态
      orderSearchLoading: false,
      supplierSearchLoading: false,
      orderSearchTimer: null,
      supplierSearchTimer: null,

      // 备注相关
      remark_dialog_visible: false,
      remarkForm: {
        content: ''
      },
      /**
       * 备注表单验证规则
       *
       * ⚠️ 数据结构说明：
       * - 后端模型：CRMOrderPurchaseRemark (kikimami_server/crm/models.py)
       * - API接口：add_crmorderpurchase_remark (CRMOrderPurchase_index.py)
       * - 返回数据结构：{ id, content, creator_name, create_at_short }
       */
      remarkRules: {
        // 备注内容验证 - 对应后端content字段
        content: [
          { required: true, message: '请输入备注内容', trigger: 'blur' }
        ]
      },
      remarkSubmitLoading: false,
      currentPurchase: null,

      // 备注历史
      remarks_dialog_visible: false,
      remarks: [],
      remarksLoading: false,

      // 详情对话框
      orderDetailVisible: false,
      supplier_detail_visible: false,
      currentOrder: {},
      selectedSupplier: null,
      orderStates: [],

      // 协作者管理
      collaborators_dialog_visible: false,
      currentPurchaseForCollaborators: null,
      currentPurchaseCollaborators: null,
      collaboratorsLoading: false,
      canManageCollaborators: false, // 是否可以管理协作者（创建者或管理员）

      // 添加协作者
      selectedNewCollaborators: [],
      availableUsers: [],
      userSearchLoading: false,
      addCollaboratorsLoading: false,
      userSearchTimer: null,

      // AI付款对话框
      aiPaymentDialogVisible: false,
      selectedPurchaseForPayment: null,
      aiCreating: false,
      aiPaymentForm: {
        payable_amount: '',
        currency: 'CNY',
        payment_date: '',
        payment_method: '',
        transaction_no: '',
        payee_account: '',
        payee_bank: '',
        notes: '',
        supplier_bank_account_id: '' // 供应商收款账号ID
      },
      aiPaymentRules: {
        payable_amount: [{ required: true, message: '请输入应付金额', trigger: 'blur' }],
        payee_account: [{ required: true, message: '请输入收款账号', trigger: 'blur' }],
        notes: [{ required: true, message: '请输入付款项目名称', trigger: 'blur' }]
      },
      // 供应商收款账号
      supplierBankAccounts: [],
      // 添加收款账号对话框
      bankAccountDialogVisible: false,
      bankAccountCreating: false,
      bankAccountForm: {
        account_name: '',
        account_number: '',
        bank_name: '',
        bank_branch: '',
        account_type: 'corporate',
        currency: 'CNY',
        payment_qrcode: '',
        notes: '',
        is_default: false
      },
      bankAccountRules: {
        account_name: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
        account_number: [{ required: true, message: '请输入收款账号', trigger: 'blur' }],
        bank_name: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
        account_type: [{ required: true, message: '请选择账户类型', trigger: 'change' }]
      },
      bankAccountQrcodeList: [],
      bankAccountQrcodeUploadData: {
        directory_name: 'supplier_payment_qrcodes',
        acl_type: '365',
        remark: '供应商收款二维码'
      }
    }
  },
  computed: {
    // AI上下文数据
    paymentAIContext() {
      if (!this.selectedPurchaseForPayment) return {}
      const purchase = this.selectedPurchaseForPayment
      const order = purchase.crmorder_data || {}
      const supplier = purchase.crmsupplier_data || {}

      return {
        // 采购单信息
        purchase_id: purchase.id,
        purchase_no: purchase.purchase_no || '',
        purchase_quantity: purchase.quantity || '',
        purchase_unit_price: purchase.unit_price || '',
        purchase_total_amount: purchase.total_amount || '',
        purchase_status: purchase.status || '',

        // 订单信息
        order_id: order.id || '',
        order_no: order.order_no || '',
        order_name: order.name || '',
        order_amount: order.order_amount || '',
        currency: order.currency || 'CNY',

        // 供应商信息
        supplier_id: supplier.id || '',
        supplier_name: supplier.name || '',
        supplier_contact: supplier.contact || '',
        supplier_email: supplier.email || '',

        // 已创建的应付账单
        existing_payables: purchase.payables || [],

        // 当前日期
        payment_date: new Date().toISOString().split('T')[0], // YYYY-MM-DD格式

        // 提示信息
        note: '请注意检查是否已有相同的应付账单，避免重复创建'
      }
    },
    // AI付款助手快捷操作
    paymentQuickActions() {
      return [
        {
          title: '历史付款',
          question: `请查询供应商"${this.selectedPurchaseForPayment?.crmsupplier_data?.name || '当前供应商'}"的历史付款情况，包括已付款金额、待付款金额、付款项目等详细信息`,
          icon: 'el-icon-document',
          color: '#409EFF'
        },
        {
          title: '收款账号',
          question: `请查询供应商"${this.selectedPurchaseForPayment?.crmsupplier_data?.name || '当前供应商'}"的所有收款账号信息，包括账号、开户行、币种等`,
          icon: 'el-icon-bank-card',
          color: '#67C23A'
        }
      ]
    },
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/crm/api/crmfile/'
    },
    uploadHeaders() {
      return {
        Authorization: getToken(),
        PTOKEN: this.$store.getters.projectId
      }
    }
  },
  created() {
    this.getList()
    this.getOptions()
    this.getStatistics()
    this.getOrderStates()
  },
  beforeDestroy() {
    // 清理计时器
    if (this.orderSearchTimer) {
      clearTimeout(this.orderSearchTimer)
    }
    if (this.supplierSearchTimer) {
      clearTimeout(this.supplierSearchTimer)
    }
    if (this.userSearchTimer) {
      clearTimeout(this.userSearchTimer)
    }
  },
  methods: {
    /**
     * 获取列表数据
     *
     * ⚠️ 数据结构说明：
     * 后端返回格式：{
     *   success: boolean,
     *   data: {
     *     data: [{ // 采购信息列表
     *       id, status, status_display, current_remark, progress,
     *       last_follow_time_short, creator_name, remarks_count,
     *       crmorder_data: { id, order_no, name, order_amount, currency },
     *       crmsupplier_data: { id, name, contact_name, contact_phone, email }
     *     }],
     *     total: number,
     *     page: number,
     *     pageSize: number
     *   }
     * }
     */
    getList() {
      this.listLoading = true
      const params = new URLSearchParams()
      params.append('page', this.page)
      params.append('pageSize', this.pagesize)
      if (this.keyword) params.append('kw', this.keyword)
      if (this.status_filter) params.append('status', this.status_filter)

      crmorderpurchase.Get(params.toString()).then(response => {
        if (response.success) {
          // 📋 解析后端返回的列表数据
          this.data = response.data.data || []
          this.total = response.data.total || 0
          // 调试：打印第一条数据的结构
          if (this.data.length > 0) {
            console.log('第一条数据结构:', this.data[0])
            console.log('供应商数据:', this.data[0].crmsupplier_data)
          }
        } else {
          this.$message.error(response.message)
        }
      }).finally(() => {
        this.listLoading = false
      })
    },

    // 获取选项数据（初始化时获取最近的一些选项）
    getOptions() {
      crmorderpurchase.GetOptions().then(response => {
        if (response.success) {
          // 远程搜索模式下，初始时不需要加载大量数据
          // 只在编辑时需要设置当前选中的选项
          this.initialOrderOptions = response.data.orders || []
          this.initialSupplierOptions = response.data.suppliers || []
        }
      })
    },

    /**
     * 获取订单状态选项 - 参考crmticket用法
     */
    getOrderStates() {
      GetOrderStates(null, qs.stringify({ all: '1' })).then(response => {
        if (response.data && response.data.data) {
          this.orderStates = response.data.data
        }
      }).catch(error => {
        console.error('获取订单状态失败:', error)
      })
    },

    /**
     * 获取统计数据
     *
     * ⚠️ 数据结构说明：
     * 后端返回格式：{
     *   success: boolean,
     *   data: {
     *     total: number,    // 总数
     *     open: number,     // 开启中数量
     *     completed: number, // 已完成数量
     *     cancelled: number  // 已取消数量
     *   }
     * }
     */
    getStatistics() {
      crmorderpurchase.GetStatistics().then(response => {
        if (response.success) {
          // 📊 解析统计数据
          this.statistics = response.data
        }
      })
    },

    // 搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },

    // 分页
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },

    handlePageChange(val) {
      this.page = val
      this.getList()
    },

    // 处理操作
    handleAction(action, data) {
      if (action === 'create') {
        this.form_dialog_title = '添加采购信息'
        this.form = {
          crmorder_id: '',
          crmsupplier_id: '',
          status: 'open',
          progress: '',
          initial_remark: ''
        }
        // 清空选项，等待用户搜索
        this.orderOptions = []
        this.supplierOptions = []
        this.form_dialog_visible = true
      } else if (action === 'edit') {
        this.form_dialog_title = '编辑采购信息'
        this.form = {
          id: data.id,
          crmorder_id: data.crmorder_data.id,
          crmsupplier_id: data.crmsupplier_data.id,
          status: data.status,
          progress: data.progress || '',
          initial_remark: ''
        }

        // 编辑时设置当前选中的选项
        this.orderOptions = [data.crmorder_data]
        this.supplierOptions = [data.crmsupplier_data]

        this.form_dialog_visible = true
      } else if (action === 'delete') {
        this.$confirm('确定要删除这条采购信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          crmorderpurchase.Delete(data.id).then(response => {
            if (response.success) {
              this.$message.success('删除成功')
              this.getList()
              this.getStatistics()
            } else {
              this.$message.error(response.msg)
            }
          })
        })
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const request = this.form.id
            ? crmorderpurchase.Put(this.form.id, this.form)
            : crmorderpurchase.Post(this.form)

          request.then(response => {
            if (response.success) {
              this.$message.success(this.form.id ? '更新成功' : '添加成功')
              this.form_dialog_visible = false
              this.getList()
              this.getStatistics()
            } else {
              this.$message.error(response.msg)
            }
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    },

    // 添加备注
    addRemark(purchase) {
      this.currentPurchase = purchase
      this.remarkForm = { content: '' }
      this.remark_dialog_visible = true
    },

    // 提交备注
    submitRemark() {
      this.$refs.remarkForm.validate((valid) => {
        if (valid) {
          this.remarkSubmitLoading = true
          crmorderpurchase.AddRemark(this.currentPurchase.id, this.remarkForm).then(response => {
            if (response.success) {
              this.$message.success('添加备注成功')
              this.remark_dialog_visible = false
              this.getList()
            } else {
              this.$message.error(response.msg)
            }
          }).finally(() => {
            this.remarkSubmitLoading = false
          })
        }
      })
    },

    // AI智能付款
    handleAddPayment(row) {
      this.selectedPurchaseForPayment = row
      this.aiPaymentDialogVisible = true
      // 币种始终默认为CNY
      this.aiPaymentForm.currency = 'CNY'
      // 加载供应商收款账号
      this.loadSupplierBankAccounts(row.crmsupplier_data?.id)
    },

    // AI填充表单
    handleAIFillForm(data) {
      if (data) {
        // 填充表单
        this.aiPaymentForm = {
          payable_amount: data.payable_amount || data.amount || this.aiPaymentForm.payable_amount,
          currency: data.currency || this.aiPaymentForm.currency,
          payment_date: data.payment_date || this.aiPaymentForm.payment_date,
          payment_method: data.payment_method || this.aiPaymentForm.payment_method,
          transaction_no: data.transaction_no || this.aiPaymentForm.transaction_no,
          payee_account: data.payee_account || this.aiPaymentForm.payee_account,
          payee_bank: data.payee_bank || this.aiPaymentForm.payee_bank,
          notes: data.notes || this.aiPaymentForm.notes
        }
        this.$message.success('已自动填充付款信息，请确认后提交')
      }
    },

    // AI JSON解析
    handleAIJsonParsed(data) {
      console.log('AI解析的JSON数据:', data)
    },

    // 确认创建应付账单
    confirmCreatePayable() {
      this.$refs.aiPaymentForm.validate(valid => {
        if (!valid) return

        this.aiCreating = true

        const data = {
          order_id: this.selectedPurchaseForPayment.crmorder_data.id,
          supplier_id: this.selectedPurchaseForPayment.crmsupplier_data.id,
          purchase_id: this.selectedPurchaseForPayment.id,
          transaction_type: '采购付款',
          payable_amount: this.aiPaymentForm.payable_amount,
          currency: this.aiPaymentForm.currency,
          expected_payment_date: this.aiPaymentForm.payment_date,
          payee_account: this.aiPaymentForm.payee_account,
          payee_bank: this.aiPaymentForm.payee_bank,
          notes: this.aiPaymentForm.notes,
          transaction_date: this.aiPaymentForm.payment_date,
          payment_method: this.aiPaymentForm.payment_method,
          reference_number: this.aiPaymentForm.transaction_no
        }

        createPayable(data).then(response => {
          if (response.success) {
            this.$message.success('应付账单创建成功')
            this.handleAIDialogClose()
            // 询问是否跳转
            this.$confirm('是否跳转到应付账单页面查看？', '提示', {
              confirmButtonText: '去查看',
              cancelButtonText: '留在当前页',
              type: 'success'
            }).then(() => {
              this.$router.push('/finance/payables')
            }).catch(() => {
              this.getList()
            })
          }
          this.aiCreating = false
        }).catch(() => {
          this.aiCreating = false
        })
      })
    },

    // 关闭AI对话框
    handleAIDialogClose() {
      this.aiPaymentDialogVisible = false
      this.aiPaymentForm = {
        payable_amount: '',
        currency: 'CNY',
        payment_date: '',
        payment_method: '',
        transaction_no: '',
        payee_account: '',
        payee_bank: '',
        notes: '',
        supplier_bank_account_id: ''
      }
      this.supplierBankAccounts = []
      // 清空AI对话
      if (this.$refs.aiInnerChat) {
        this.$refs.aiInnerChat.clearMessages()
      }
    },

    // 加载供应商收款账号
    loadSupplierBankAccounts(supplierId) {
      if (!supplierId) {
        this.supplierBankAccounts = []
        return
      }
      getSupplierBankAccounts({ supplier_id: supplierId, is_active: true }).then(response => {
        if (response.success) {
          this.supplierBankAccounts = response.data || []
          // 如果有默认账号，自动选中
          const defaultAccount = this.supplierBankAccounts.find(acc => acc.is_default)
          if (defaultAccount) {
            this.aiPaymentForm.supplier_bank_account_id = defaultAccount.id
            this.handleBankAccountChange(defaultAccount.id)
          }
        }
      }).catch(() => {
        this.$message.error('加载收款账号失败')
      })
    },

    // 收款账号选择变化
    handleBankAccountChange(accountId) {
      if (!accountId) {
        return
      }
      const account = this.supplierBankAccounts.find(acc => acc.id === accountId)
      if (account) {
        // 自动填充收款账号和开户银行信息
        this.aiPaymentForm.payee_account = account.account_number
        this.aiPaymentForm.payee_bank = account.bank_name
      }
    },

    // 显示添加收款账号对话框
    showAddBankAccountDialog() {
      if (!this.selectedPurchaseForPayment?.crmsupplier_data?.id) {
        this.$message.warning('请先选择供应商')
        return
      }
      this.bankAccountDialogVisible = true
    },

    // 关闭收款账号对话框
    handleBankAccountDialogClose() {
      this.bankAccountDialogVisible = false
      this.bankAccountForm = {
        account_name: '',
        account_number: '',
        bank_name: '',
        bank_branch: '',
        account_type: 'corporate',
        currency: 'CNY',
        payment_qrcode: '',
        notes: '',
        is_default: false
      }
      this.bankAccountQrcodeList = []
      if (this.$refs.bankAccountForm) {
        this.$refs.bankAccountForm.resetFields()
      }
    },

    // 二维码上传成功
    handleBankAccountQrcodeSuccess(response, file, fileList) {
      if (response.success) {
        this.bankAccountQrcodeList = fileList
        this.bankAccountForm.payment_qrcode = response.data.url
        this.$message.success('二维码上传成功')
      }
    },

    // 二维码删除
    handleBankAccountQrcodeRemove(file, fileList) {
      this.bankAccountQrcodeList = fileList
      this.bankAccountForm.payment_qrcode = ''
    },

    // 二维码上传前验证
    beforeBankAccountQrcodeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt10M) {
        this.$message.error('图片大小不能超过 10MB!')
      }
      return isImage && isLt10M
    },

    // 确认创建收款账号
    confirmCreateBankAccount() {
      this.$refs.bankAccountForm.validate(valid => {
        if (!valid) return

        this.bankAccountCreating = true

        const data = {
          supplier_id: this.selectedPurchaseForPayment.crmsupplier_data.id,
          ...this.bankAccountForm
        }

        createSupplierBankAccount(data).then(response => {
          if (response.success) {
            this.$message.success('收款账号创建成功')
            this.handleBankAccountDialogClose()
            // 重新加载收款账号列表
            this.loadSupplierBankAccounts(this.selectedPurchaseForPayment.crmsupplier_data.id)
          }
          this.bankAccountCreating = false
        }).catch(() => {
          this.bankAccountCreating = false
        })
      })
    },

    /**
     * 显示备注历史
     *
     * ⚠️ 数据结构说明：
     * 后端返回格式：{
     *   success: boolean,
     *   data: {
     *     data: [{ // 备注历史列表
     *       id: number,
     *       content: string,
     *       creator_name: string,
     *       create_at_short: string
     *     }]
     *   }
     * }
     *
     * @param {Object} purchase - 采购信息对象
     */
    showRemarksHistory(purchase) {
      // 先显示对话框和loading状态
      this.remarks = []
      this.remarks_dialog_visible = true
      this.remarksLoading = true

      // 然后获取数据
      crmorderpurchase.GetRemarks(purchase.id).then(response => {
        if (response.success) {
          // 📝 解析备注历史数据 - 根据axios拦截器处理，使用response.data.data
          this.remarks = response.data.data || []
          // 🔍 Debug: 输出备注数据查看结构
          console.log('备注历史数据:', this.remarks)
        } else {
          this.$message.error(response.msg || '获取备注历史失败')
        }
      }).catch(error => {
        console.error('获取备注历史失败:', error)
        this.$message.error('获取备注历史失败')
      }).finally(() => {
        this.remarksLoading = false
      })
    },

    /**
     * 处理备注历史对话框关闭事件
     */
    handleRemarksDialogClose() {
      // 重置状态
      this.remarksLoading = false
      this.remarks = []
    },

    /**
     * 显示订单详情 - 参考crmticket用法
     * @param {Object} order - 订单数据
     */
    async showOrderDetail(order) {
      console.log('showOrderDetail 接收到的订单数据:', order)

      if (!order) {
        this.$message.warning('订单数据为空')
        return
      }

      // 验证是否有订单ID
      if (!order.id) {
        console.error('订单数据缺少 id 字段:', order)
        this.$message.error('订单数据不完整，缺少订单ID')
        return
      }

      // 从后端获取完整的订单数据 - 参考crmticket用法
      try {
        const loading = this.$loading({
          lock: true,
          text: '加载订单详情...',
          spinner: 'el-icon-loading'
        })

        const response = await GetCrmOrder(order.id)
        loading.close()

        if (response.data && response.data.success && response.data.data) {
          this.currentOrder = response.data.data
          this.orderDetailVisible = true
        } else {
          this.$message.error('获取订单详情失败')
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败: ' + (error.message || '网络错误'))
      }
    },

    // 显示供应商详情
    showSupplierDetail(supplier) {
      console.log('显示供应商详情，数据:', supplier)
      if (!supplier) {
        this.$message.warning('供应商信息为空')
        return
      }
      this.selectedSupplier = supplier
      this.supplier_detail_visible = true
    },

    // 显示统计信息
    showStatistics() {
      this.getStatistics()
      this.$message.success('统计信息已刷新')
    },

    /**
     * 搜索订单
     *
     * ⚠️ 数据结构说明：
     * 后端返回格式：{
     *   success: boolean,
     *   msg: string,
     *   data: [{ // 订单搜索结果 - 注意：搜索API直接返回数组，不是嵌套结构
     *     id: number,
     *     order_no: string,
     *     name: string,
     *     order_amount: string,
     *     currency: string
     *   }]
     * }
     *
     * @param {string} query - 搜索关键词
     */
    searchOrders(query) {
      if (!query || query.trim() === '') {
        this.orderOptions = []
        return
      }

      // 防抖处理
      clearTimeout(this.orderSearchTimer)
      this.orderSearchTimer = setTimeout(() => {
        this.orderSearchLoading = true
        crmorderpurchase.SearchOrders(query.trim()).then(response => {
          if (response.success) {
            // 📋 解析订单搜索结果 - 搜索API直接返回数组在data字段
            this.orderOptions = response.data || []
          } else {
            this.$message.error(response.msg || '搜索订单失败')
            this.orderOptions = []
          }
        }).catch(() => {
          this.$message.error('搜索订单失败')
          this.orderOptions = []
        }).finally(() => {
          this.orderSearchLoading = false
        })
      }, 300) // 300ms防抖
    },

    /**
     * 搜索供应商
     *
     * ⚠️ 数据结构说明：
     * 后端返回格式：{
     *   success: boolean,
     *   msg: string,
     *   data: [{ // 供应商搜索结果 - 注意：搜索API直接返回数组，不是嵌套结构
     *     id: number,
     *     name: string,
     *     contact_name: string,
     *     contact_phone: string,
     *     email: string
     *   }]
     * }
     *
     * @param {string} query - 搜索关键词
     */

    // ===== 快速编辑功能 =====

    /**
     * 快速编辑备注 - 点击内容直接编辑
     * 支持多行文本输入，Ctrl+Enter保存，失焦取消
     * @param {Object} row - 行数据
     */
    editRemark(row) {
      // 设置编辑状态
      this.$set(row, 'editingRemark', true)
      this.$set(row, 'tempRemark', row.current_remark || '')
      // 下一个tick聚焦到文本框
      this.$nextTick(() => {
        // 找到对应的文本框并聚焦
        const textareas = document.querySelectorAll('.edit-remark-container .el-textarea__inner')
        if (textareas.length > 0) {
          const textarea = textareas[textareas.length - 1]
          textarea.focus()
          // 将光标移到文本末尾
          textarea.setSelectionRange(textarea.value.length, textarea.value.length)
        }
      })
    },

    /**
     * 保存快速备注
     * @param {Object} row - 行数据
     */
    saveQuickRemark(row) {
      if (!row.tempRemark || row.tempRemark.trim() === '') {
        this.$message.warning('请输入备注内容')
        return
      }

      // 调用添加备注接口
      const remarkData = {
        content: row.tempRemark.trim()
      }

      crmorderpurchase.AddRemark(row.id, remarkData).then(response => {
        if (response.success) {
          this.$message.success('备注更新成功')
          // 更新显示数据
          row.current_remark = row.tempRemark.trim()
          row.remarks_count = (row.remarks_count || 0) + 1
          // 退出编辑状态
          this.cancelEditRemark(row)
          // 刷新列表以获取最新的跟进时间
          this.getList()
        } else {
          this.$message.error(response.msg || '备注更新失败')
        }
      }).catch(() => {
        this.$message.error('备注更新失败')
      })
    },

    /**
     * 取消编辑备注
     * @param {Object} row - 行数据
     */
    cancelEditRemark(row) {
      this.$set(row, 'editingRemark', false)
      this.$set(row, 'tempRemark', '')
    },

    /**
     * 处理备注输入框失焦事件
     * @param {Object} row - 行数据
     * @param {Event} event - 失焦事件
     */
    handleRemarkBlur(row, event) {
      // 延迟执行，如果用户点击了保存或取消按钮，则不执行取消操作
      setTimeout(() => {
        if (row.editingRemark) {
          this.cancelEditRemark(row)
        }
      }, 150)
    },

    /**
     * 快速编辑进展 - 点击内容直接编辑
     * 支持多行文本输入，Ctrl+Enter保存，失焦取消
     * @param {Object} row - 行数据
     */
    editProgress(row) {
      // 设置编辑状态
      this.$set(row, 'editingProgress', true)
      this.$set(row, 'tempProgress', row.progress || '')
      // 下一个tick聚焦到文本框
      this.$nextTick(() => {
        // 找到对应的文本框并聚焦
        const textareas = document.querySelectorAll('.edit-progress-container .el-textarea__inner')
        if (textareas.length > 0) {
          const textarea = textareas[textareas.length - 1]
          textarea.focus()
          // 将光标移到文本末尾
          textarea.setSelectionRange(textarea.value.length, textarea.value.length)
        }
      })
    },

    /**
     * 保存快速进展
     * @param {Object} row - 行数据
     */
    saveQuickProgress(row) {
      const progressValue = row.tempProgress ? row.tempProgress.trim() : ''

      // 调用更新接口
      const updateData = {
        status: row.status,
        progress: progressValue
      }

      crmorderpurchase.Put(row.id, updateData).then(response => {
        if (response.success) {
          this.$message.success('进展更新成功')
          // 更新显示数据
          row.progress = progressValue
          // 退出编辑状态
          this.cancelEditProgress(row)
          // 刷新列表以获取最新的跟进时间
          this.getList()
        } else {
          this.$message.error(response.msg || '进展更新失败')
        }
      }).catch(() => {
        this.$message.error('进展更新失败')
      })
    },

    /**
     * 取消编辑进展
     * @param {Object} row - 行数据
     */
    cancelEditProgress(row) {
      this.$set(row, 'editingProgress', false)
      this.$set(row, 'tempProgress', '')
    },

    /**
     * 处理进展输入框失焦事件
     * @param {Object} row - 行数据
     * @param {Event} event - 失焦事件
     */
    handleProgressBlur(row, event) {
      // 延迟执行，如果用户点击了保存或取消按钮，则不执行取消操作
      setTimeout(() => {
        if (row.editingProgress) {
          this.cancelEditProgress(row)
        }
      }, 150)
    },

    // ===== 搜索功能 =====

    searchSuppliers(query) {
      if (!query || query.trim() === '') {
        this.supplierOptions = []
        return
      }

      // 防抖处理
      clearTimeout(this.supplierSearchTimer)
      this.supplierSearchTimer = setTimeout(() => {
        this.supplierSearchLoading = true
        crmorderpurchase.SearchSuppliers(query.trim()).then(response => {
          if (response.success) {
            // 📋 解析供应商搜索结果 - 搜索API直接返回数组在data字段
            this.supplierOptions = response.data || []
          } else {
            this.$message.error(response.msg || '搜索供应商失败')
            this.supplierOptions = []
          }
        }).catch(() => {
          this.$message.error('搜索供应商失败')
          this.supplierOptions = []
        }).finally(() => {
          this.supplierSearchLoading = false
        })
      }, 300) // 300ms防抖
    },

    // ===== 协作者管理功能 =====

    /**
     * 管理协作者
     * @param {Object} purchase - 采购信息对象
     */
    manageCollaborators(purchase) {
      this.currentPurchaseForCollaborators = purchase
      this.currentPurchaseCollaborators = null
      this.selectedNewCollaborators = []
      this.availableUsers = []
      this.collaborators_dialog_visible = true
      this.collaboratorsLoading = true

      // 获取协作者信息
      this.getCollaboratorsInfo(purchase.id)
    },

    /**
     * 获取协作者信息
     * @param {number} purchaseId - 采购信息ID
     */
    getCollaboratorsInfo(purchaseId) {
      crmorderpurchase.GetCollaborators(purchaseId).then(response => {
        try {
          if (response.success) {
            this.currentPurchaseCollaborators = response.data

            // 获取当前用户信息并判断权限
            this.$store.dispatch('GetUserInfo').then((response) => {
              // 从API响应中直接获取用户信息（包含ID）
              const currentUser = response.data
              console.log('当前用户信息:', currentUser)
              console.log('协作者数据中的创建者:', this.currentPurchaseCollaborators.creator)

              if (!currentUser || !currentUser.id) {
                console.error('当前用户信息无效')
                this.canManageCollaborators = false
                return
              }

              // 判断是否为创建者（通过用户ID比较）
              const isCreator = this.currentPurchaseCollaborators.creator &&
                               this.currentPurchaseCollaborators.creator.id === currentUser.id

              // 判断是否为管理员
              const isManager = currentUser.roles &&
                               (currentUser.roles.includes('crm_manager') || currentUser.roles.includes('admin'))

              console.log('是否为创建者:', isCreator)
              console.log('是否为管理员:', isManager)

              this.canManageCollaborators = isCreator || isManager
              console.log('是否可以管理协作者:', this.canManageCollaborators)
            }).catch(error => {
              console.error('获取用户信息失败:', error)
              this.canManageCollaborators = false
            })
          } else {
            this.$message.error(response.msg || '获取协作者信息失败')
          }
        } catch (parseError) {
          console.error('解析协作者数据失败:', parseError)
          this.$message.error('解析协作者数据失败')
        }
      }).catch(error => {
        console.error('获取协作者信息失败:', error)
        this.$message.error('获取协作者信息失败')
      }).finally(() => {
        this.collaboratorsLoading = false
      })
    },

    /**
     * 搜索项目用户
     * @param {string} query - 搜索关键词
     */
    searchProjectUsers(query) {
      if (!query || query.trim() === '') {
        this.availableUsers = []
        return
      }

      // 防抖处理
      clearTimeout(this.userSearchTimer)
      this.userSearchTimer = setTimeout(() => {
        this.userSearchLoading = true
        crmorderpurchase.SearchProjectUsers(query.trim()).then(response => {
          if (response.success) {
            this.availableUsers = response.data.data || []
          } else {
            this.$message.error(response.msg || '搜索用户失败')
            this.availableUsers = []
          }
        }).catch(() => {
          this.$message.error('搜索用户失败')
          this.availableUsers = []
        }).finally(() => {
          this.userSearchLoading = false
        })
      }, 300)
    },

    /**
     * 检查用户是否已经是协作者
     * @param {number} userId - 用户ID
     * @returns {boolean} - 是否已是协作者
     */
    isUserAlreadyCollaborator(userId) {
      if (!this.currentPurchaseCollaborators || !this.currentPurchaseCollaborators.collaborators) {
        return false
      }

      // 检查是否已是协作者
      const isCollaborator = this.currentPurchaseCollaborators.collaborators.some(c => c.id === userId)

      // 检查是否是创建者
      const isCreator = this.currentPurchaseCollaborators.creator &&
                       this.currentPurchaseCollaborators.creator.id === userId

      return isCollaborator || isCreator
    },

    /**
     * 处理协作者选择变化
     */
    handleCollaboratorSelection() {
      // 可以在这里添加选择变化的处理逻辑
      console.log('选中的协作者:', this.selectedNewCollaborators)
    },

    /**
     * 添加协作者
     */
    addCollaborators() {
      if (!this.selectedNewCollaborators || this.selectedNewCollaborators.length === 0) {
        this.$message.warning('请选择要添加的协作者')
        return
      }

      this.addCollaboratorsLoading = true

      const data = {
        user_ids: this.selectedNewCollaborators
      }

      crmorderpurchase.AddCollaborators(this.currentPurchaseForCollaborators.id, data).then(response => {
        if (response.success) {
          this.$message.success(`成功添加 ${this.selectedNewCollaborators.length} 个协作者`)
          // 重新获取协作者信息
          this.getCollaboratorsInfo(this.currentPurchaseForCollaborators.id)
          // 清空选择
          this.selectedNewCollaborators = []
          this.availableUsers = []
          // 刷新列表
          this.getList()
        } else {
          this.$message.error(response.msg || '添加协作者失败')
        }
      }).catch(() => {
        this.$message.error('添加协作者失败')
      }).finally(() => {
        this.addCollaboratorsLoading = false
      })
    },

    /**
     * 移除协作者
     * @param {number} userId - 要移除的用户ID
     */
    removeCollaborator(userId) {
      this.$confirm('确定要移除这个协作者吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          user_ids: [userId]
        }

        crmorderpurchase.RemoveCollaborators(this.currentPurchaseForCollaborators.id, data).then(response => {
          if (response.success) {
            this.$message.success('移除协作者成功')
            // 重新获取协作者信息
            this.getCollaboratorsInfo(this.currentPurchaseForCollaborators.id)
            // 刷新列表
            this.getList()
          } else {
            this.$message.error(response.msg || '移除协作者失败')
          }
        }).catch(() => {
          this.$message.error('移除协作者失败')
        })
      })
    }
  }
}
</script>

<style scoped>
/* 统计信息栏样式 */
.statistics-bar {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px 20px;
  margin-bottom: 15px;
  gap: 30px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  min-width: 20px;
  text-align: center;
}

.stat-pending {
  color: #E6A23C;
}

.stat-open {
  color: #409EFF;
}

.stat-completed {
  color: #67C23A;
}

.stat-cancelled {
  color: #F56C6C;
}

.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

/* 订单信息单元格样式 */
.order-info-cell {
  width: 100%;
}

.order-info-line {
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.order-name-bracket {
  color: #606266;
  font-size: 13px;
  margin-left: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  min-width: 0;
}

.order-state-name {
  font-size: 12px;
  font-weight: 500;
  margin-left: 4px;
  white-space: nowrap;
}

/* 备注单元格样式 */
.remark-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 快速编辑容器样式 */
.edit-remark-container,
.edit-progress-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 8px;
}

.show-remark-container,
.show-progress-container {
  display: flex;
  align-items: flex-start;
  width: 100%;
  min-height: 40px;
}

/* 内容区域样式 */
.remark-content,
.progress-content {
  flex: 1;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  margin-right: 8px;
  min-height: 32px;
  display: flex;
  align-items: center;
}

.remark-content:hover,
.progress-content:hover {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
}

.remark-text,
.progress-text {
  word-wrap: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
  color: #606266;
}

.remark-content .remark-text:empty::before,
.progress-content .progress-text:empty::before {
  content: attr(placeholder);
  color: #c0c4cc;
}

/* 编辑按钮组样式 */
.edit-buttons {
  display: flex;
  gap: 5px;
  align-self: flex-start;
  margin-top: 2px;
}

.edit-buttons .el-button {
  padding: 5px 8px;
  min-width: auto;
}

/* 历史按钮样式 */
.show-remark-container .el-button--text {
  padding: 0 5px;
  font-size: 12px;
  min-width: auto;
  align-self: flex-start;
  margin-top: 8px;
}

/* 输入框样式 */
.edit-remark-container .el-textarea,
.edit-progress-container .el-textarea {
  flex: 1;
}

.edit-remark-container .el-textarea .el-textarea__inner,
.edit-progress-container .el-textarea .el-textarea__inner {
  resize: vertical;
  min-height: 60px;
}

/* 备注占位符样式 */
.remark-placeholder {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
  opacity: 0.8;
}

/* 进展占位符样式 */
.progress-placeholder {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
  opacity: 0.8;
}

.mt-pagination {
  margin-top: 20px;
  text-align: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

/* 协作者相关样式 */
.collaborators-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  min-height: 40px;
}

.collaborators-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 2px;
  margin-bottom: 2px;
}

.more-collaborators {
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  border-radius: 10px;
  padding: 2px 6px;
  margin-left: 2px;
}

.no-collaborators {
  font-size: 12px;
  color: #C0C4CC;
  font-style: italic;
}

.creator-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.no-creator {
  color: #C0C4CC;
  font-style: italic;
}

.collaborators-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background-color: #fafafa;
}

.current-collaborators {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 4px;
}

.empty-collaborators {
  text-align: center;
  padding: 30px;
}

.add-collaborators-section {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.add-collaborators-form {
  width: 100%;
}

.add-buttons {
  text-align: left;
}

.no-permission-tip {
  padding: 20px;
  text-align: center;
}

/* 删除原来的卡片样式，改用紧凑的统计栏 */

/* 时间线样式 */
.el-timeline-item__timestamp {
  color: #909399;
  font-size: 13px;
}

/* 供应商微信群名样式 */
.supplier-wechatgroup {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
  line-height: 1.2;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* AI付款抽屉样式 */
.payment-drawer-content-split {
  display: flex;
  height: 100%;
  gap: 20px;
  padding: 0 20px 20px;
}

/* 左侧表单面板 (60%) */
.left-panel-form {
  flex: 0 0 60%;
  overflow-y: auto;
  padding-right: 10px;
}

/* 右侧 AI 助手面板 (40%) */
.right-panel-ai {
  flex: 0 0 40%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #EBEEF5;
  padding-left: 20px;
  overflow: hidden;
  min-height: 0; /* 确保flex子元素可以正确收缩 */
}

.ai-panel-header {
  padding: 10px 0 15px;
  border-bottom: 2px solid #1EB7E6;
  margin-bottom: 15px;
  flex-shrink: 0;
}

/* AIInnerChat组件需要填充剩余空间 */
.right-panel-ai ::v-deep .ai-inner-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

/* 确保消息列表可以滚动 */
.right-panel-ai ::v-deep .message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

/* 输入区域固定在底部 */
.right-panel-ai ::v-deep .input-area {
  flex-shrink: 0;
  margin-top: 15px;
}

/* 采购单信息显示 */
.purchase-info-content {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  line-height: 32px;
}

.info-label {
  color: #606266;
  font-weight: 500;
  min-width: 80px;
}

.info-value {
  color: #303133;
  flex: 1;
}

/* 表单底部按钮 */
.form-footer {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 深度选择器 - 调整抽屉内部样式 */
::v-deep .el-drawer__body {
  padding: 20px 0;
  overflow: hidden;
}
</style>
